#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <ctime>
#define NUM 5
enum class Status 
{
    OK = 0,
    ERROR
};

//线程信息类
class ThreadData 
{
public:
    ThreadData(const std::string &name, int id, int n)
    :_name(name)
    ,_id(id)
    ,_createTime(time(nullptr))
    ,_n(n)
    ,_result(0)
    ,_status(Status::OK) {}

public:
    std::string _name;
    int _id;
    time_t _createTime;
    int _n;
    int _result;
    Status _status;

};

//线程回调函数
void* threadRun(void* arg) {
    ThreadData *td = static_cast<ThreadData*>(arg);

    for(int i = 0; i <= td->_n; i++) {
        td->_result += i;
    }

    std::cout << "线程" << td->_name << " ID " << td->_id << " CreatrTime " << td->_createTime << " done..." << std::endl;
    pthread_exit((void*)td);
}

int main() 
{
    pthread_t pt[NUM];
    for(int i = 0; i < NUM; i++) {
        char name[64];
        snprintf(name, sizeof(name), "thread-%d", i + 1);

        //创建对象
        ThreadData *td = new ThreadData(name, i, 100 * (10 + i));
        pthread_create(pt + i, nullptr, threadRun, td);
        sleep(1);
    }

    void *retval = nullptr;
    for(int i = 0; i < NUM; i++) {
        int ret = pthread_join(pt[i], &retval);
        if(ret != 0)
            std::cerr << "线程等待" << pt[i] << "失败" << std::endl;

        ThreadData *td = static_cast<ThreadData*>(retval);

        if(td->_status == Status::OK)
            std::cout << "线程" << pt[i] << "计算 [0, " << td->_n << "] 的累加结果为" << td->_result << std::endl;
        delete td;
    }
    std::cout << "所有的线程都退出了" << std::endl;
    return 0;
}